// pages/index/nearbyInstitutions/nearbyInstitutions.js
import request from '../../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    institution:'',
    distances:[],
    jingwei:[],
    institutions: [
     
    ],
    latitude: 34.818510,
    longitude: 113.561538
  },
// 定义一个函数，根据地址用来获取经纬度
  getLocation2(add) {
  wx.request({
    url: 'https://restapi.amap.com/v3/geocode/geo',
    method:"GET",
    data:{
      key: 'cd2aeb25b049ef42261f6adb2caea630',
      address: add
    },
    success:(resp)=>{
      let location = resp.data.geocodes[0].location
      console.log(location)

    },
    fail:(err)=>{
      console.error('请求失败：', err);
    }
  })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.selectinstitutions();
    this.getLocation();
  },
  selectinstitutions(){
    let that=this;
    request({
      url: 'system/institution/list',
      method: "GET",
      data:{
        name:this.data.institution
      },
      success: (result) => {
        console.log(result.data.rows)
        this.setData({
          institutions:result.data.rows
        })
        for(let i=0;i<result.data.rows.length;i++){
          let add=result.data.rows[i].address;
          wx.request({
            url: 'https://restapi.amap.com/v3/geocode/geo',
            method:"GET",
            data:{
              key: 'cd2aeb25b049ef42261f6adb2caea630',
              address: add
            },
            success:(resp)=>{
              let location = resp.data.geocodes[0].location
              let jing1=that.data.longitude;
              let wei1=that.data.latitude;
              let jing2=location.split(',')[0];
              let wei2=location.split(',')[1];
              let dist=this.getDistance(wei1,jing1,wei2,jing2)
              console.log(Math.round(dist/1000))
              const newd=[Math.round(dist/1000)];
              this.setData({
                distances:[...that.data.distances,...newd]
              })
            },
            fail:(err)=>{
              console.error('请求失败：', err);
            }
          })
          
          
        }
      },
      fail: (err) => {},
      complete: (res) => {},
    })
  },
  bindserach(e){
    this.setData({
      institution: e.detail.value
    });
    this.selectinstitutions();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 获取当前位置
  getLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        this.getNearbyInstitutions();
      },
      fail: () => {
        wx.showToast({
          title: '请开启位置权限',
          icon: 'none'
        });
      }
    });
  },
  getDistance(lat1, lon1, lat2, lon2) {
    const R = 6371e3; // 地球半径，单位：米
    const φ1 = lat1 * Math.PI / 180;
    const φ2 = lat2 * Math.PI / 180;
    const Δφ = (lat2 - lat1) * Math.PI / 180;
    const Δλ = (lon2 - lon1) * Math.PI / 180;
  
    const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
              Math.cos(φ1) * Math.cos(φ2) *
              Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  
    const distance = R * c;
    return distance;
  },
  
  // 获取附近机构列表
  getNearbyInstitutions() {
    // 这里可以调用后端接口获取附近机构列表
    // 使用this.data.latitude和this.data.longitude作为参数
  },

  // 点击机构卡片
  onInstitutionClick(e) {
    let id  = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `./institutionDetail/institutionDetail?id=`+id
    });
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    // 可以实现实时搜索或等待用户点击搜索按钮
  }
})